﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ESRI.ArcGIS.Geodatabase;
using System.Collections;
using System.Windows.Forms;
using ESRI.ArcGIS.Geometry;


using PlanningGIS.Util.Collections;
using PlanningGIS.Framework.Rule;
using PlanningGIS.Util.Log;

namespace PlanningGIS.DataConvert.model
{
   
    public class DlgDataImportMatch : DataConstruct
    {
        //前缀
        private string prefix = "";
        private bool preTarOrSur = false;

        //后缀
        private string postfix="";
        private bool postTarOrSur=false;


        public string Prefix
        {
            set { prefix = value; }
        }

        public bool PreTarOrSur
        {
            set { preTarOrSur = value; }
        }

        public string Postfix
        {
            set { postfix = value; }
        }

        public bool PostTarOrSur
        {
            set { postTarOrSur = value; }
        }

        /// <summary>
        /// 条件判断
        /// </summary>
        /// <returns></returns>
        private bool Validate()
        {
            if (FeatClsListSource == null || FeatClsListSource.Count == 0)
            {
               LogHelper.WriteErrLog("请设置数据源！");
                return false;
            }

            if (FeatClsListTarget == null || FeatClsListTarget.Count == 0)
            {
               LogHelper.WriteErrLog("请设置目标数据！");
                return false;
            }

            DlgDataConverts = new List<DlgDataConvert>();

            return true;
        }

        /// <summary>
        /// 根据图层名称和字段名称进行自动匹配
        /// </summary>
        /// <returns></returns>
        public bool MatchAutomatic()
        {
            if (!Validate()) return false;

            SetProcessBarMax(FeatClsListTarget.Count);
            int i=0;

            #region 循环目标数据图层
            foreach (IFeatureClass pFeatClsTarget in FeatClsListTarget)
            {
                SetProcessBarCurrent(++i);

                DlgDataConvert dlgDataConvert;
                dlgDataConvert = new DlgDataConvert();
                dlgDataConvert.NeedDelete = NeedDelete;
                dlgDataConvert.SetProcessBarMax = SetProcessBarMax;
                dlgDataConvert.SetProcessBarCurrent = SetProcessBarCurrent;
                
                dlgDataConvert.TargetFeatCls = pFeatClsTarget;
                
                Hashtable fieldRelation = new Hashtable();

                bool hasFoundClass = false;

                #region 循环数据源图层
                foreach (IFeatureClass pFeatClsSource in FeatClsListSource)
                {
                    string source = (pFeatClsSource as IDataset).Name;
                    if (source.Contains('.')) source = source.Substring(source.LastIndexOf('.') + 1);
                    string target = (pFeatClsTarget as IDataset).Name;
                    if (target.Contains('.')) target = target.Substring(target.LastIndexOf('.') + 1);

                    //added at 2009-05-12 增加前缀和后缀，自动匹配更灵活
                    if (preTarOrSur)
                        target = prefix + target;
                    else
                        source = prefix + source;

                    if (postTarOrSur)
                        target = target + postfix;
                    else
                        source = source + postfix;
                   
                    if ((source.ToUpper() == target.ToUpper ()) && 
                        (pFeatClsTarget.FeatureType == pFeatClsSource.FeatureType) && 
                        (pFeatClsTarget.ShapeType == pFeatClsSource.ShapeType))
                    {
                        dlgDataConvert.SourceFeatCls = pFeatClsSource;
                        hasFoundClass = true;

                        for (int j = 0; j < pFeatClsTarget.Fields.FieldCount; j++)
                        {
                            bool hasFoundField = false;
                            IField pFieldTarget = pFeatClsTarget.Fields.get_Field(j);
                            if (pFieldTarget.Editable && pFieldTarget.Type !=esriFieldType.esriFieldTypeGeometry )
                            {
                                for (int k = 0; k < pFeatClsSource.Fields.FieldCount; k++)
                                {
                                    IField pFieldSource = pFeatClsSource.Fields.get_Field(k);

                                    if (pFieldTarget.Name.ToUpper() == pFieldSource.Name.ToUpper())
                                    {
                                        hasFoundField = true;
                                        fieldRelation.Add(pFieldTarget.Name ,pFieldSource.Name );
                                        break;
                                    }
                                }
                                //如果在数据源图层中没有找到对应的字段，则默认给一个空字符串（""）
                                if (!hasFoundField)
                                    fieldRelation.Add(pFieldTarget.Name, "");
                            }
                        }
                        break;
                    }
                }

                //如果没有找到相应的数据源
                if (hasFoundClass == false)
                {
                    for (int j = 0; j < pFeatClsTarget.Fields.FieldCount; j++)
                    {
                        if (pFeatClsTarget.Fields.get_Field(j).Editable &&  pFeatClsTarget.Fields.get_Field(j).Type !=esriFieldType.esriFieldTypeGeometry )
                            fieldRelation.Add(pFeatClsTarget.Fields.get_Field(j).Name, "");
                    }
                }

                dlgDataConvert.FieldRelation = fieldRelation;

                DlgDataConverts.Add(dlgDataConvert);

                #endregion

            }
            #endregion

            return true;
        }


        /// <summary>
        /// 根据规则进行匹配
        /// </summary>
        /// <param name="dataMatchRule"></param>
        /// <returns></returns>
        public bool MatchByRule(DataMatchRule dataMatchRule)
        {
            if (!Validate()) return false;

            if (dataMatchRule == null) return false;

            if (dataMatchRule.dlgTargetMatchFeatureClass == null || dataMatchRule.dlgTargetMatchFeatureClass.Count == 0) return false;

            SetProcessBarMax(FeatClsListTarget.Count);
            int i = 0;

            #region 循环目标数据图层
            foreach (IFeatureClass pFeatClsTarget in FeatClsListTarget)
            {
                SetProcessBarCurrent(++i);

                DlgDataConvert dlgDataConvert;
                dlgDataConvert = new DlgDataConvert();
                dlgDataConvert.NeedDelete = NeedDelete;
                dlgDataConvert.SetProcessBarMax = SetProcessBarMax;
                dlgDataConvert.SetProcessBarCurrent = SetProcessBarCurrent;
                
                Hashtable fieldRelation = new Hashtable();

                bool hasFoundClass = false;

                DlgTargetMatchFeatureClass dlgTargetMatchFeatureClass = ListHelper.GetEnumeratorItem(dataMatchRule.dlgTargetMatchFeatureClass, 
                    "FeatureClassName", (pFeatClsTarget as IDataset).Name);

                dlgDataConvert.TargetFeatCls = pFeatClsTarget;

                if (dlgTargetMatchFeatureClass != null)
                {
                    foreach (IFeatureClass pFeatClsSource in FeatClsListSource)
                    {
                        if (dlgTargetMatchFeatureClass.SourceFeatClsName.Trim () == (pFeatClsSource as IDataset).Name &&
                            (pFeatClsTarget.FeatureType == pFeatClsSource.FeatureType) &&
                            (pFeatClsTarget.ShapeType == pFeatClsSource.ShapeType))
                        {
                            dlgDataConvert.SourceFeatCls = pFeatClsSource;
                            hasFoundClass = true;
                            break;
                        }
                    }
                }

                if (hasFoundClass)
                {
                    for (int j = 0; j < pFeatClsTarget.Fields.FieldCount; j++)
                    {
                        bool hasFoundField = false;
                        IField pFieldTarget = pFeatClsTarget.Fields.get_Field(j);

                        if (!pFieldTarget.Editable|| pFieldTarget.Type == esriFieldType.esriFieldTypeGeometry) continue ;
                        AttrField attrField = ListHelper.GetEnumeratorItem(dlgTargetMatchFeatureClass.attrFields, "TargetFieldName", pFieldTarget.Name);
                        if (attrField == null)
                        {
                            fieldRelation.Add(pFeatClsTarget.Fields.get_Field(j).Name, "");
                        }
                        else
                        {
                            for (int k = 0; k < dlgDataConvert.SourceFeatCls.Fields.FieldCount; k++)
                            {
                                IField pFieldSource = dlgDataConvert.SourceFeatCls.Fields.get_Field(k);
                                if (pFieldSource.Name == attrField.SourceFieldName.Trim ())
                                {
                                    hasFoundField = true;
                                    fieldRelation.Add(pFieldTarget.Name, pFieldSource.Name);
                                    break;
                                }
                            }

                            //如果在数据源图层中没有找到规则中对应的字段，则默认给一个空字符串（""）
                            if (!hasFoundField)
                            {
                                fieldRelation.Add(pFieldTarget.Name, "");
                            }
                        }
                    }

                }
                //如果没有找到相应的数据源
                else 
                {
                    for (int j = 0; j < pFeatClsTarget.Fields.FieldCount; j++)
                    {
                        if (pFeatClsTarget.Fields.get_Field(j).Editable && pFeatClsTarget.Fields.get_Field(j).Type != esriFieldType.esriFieldTypeGeometry)
                            fieldRelation.Add(pFeatClsTarget.Fields.get_Field(j).Name, "");
                    }
                }

                dlgDataConvert.FieldRelation = fieldRelation;

                DlgDataConverts.Add(dlgDataConvert);
            }
            #endregion

            return true;
        }
    }
}
